#include "../apue.h"
#include <sys/wait.h>
#include <signal.h>

void pr_siginfo(siginfo_t * siginfo);

#define WAIT_FLAG (WCONTINUED | WEXITED | WSTOPPED)

int main(void)
{
    pid_t pid;
    int status;
    siginfo_t sif;

    if ((pid = fork()) < 0)
        err_sys("fork error");
    else if (pid == 0)
        exit(7);

    if (waitid(P_PID, pid, &sif, WAIT_FLAG ) < 0)
        err_sys("wait error");
    pr_siginfo(&sif);

    if ((pid = fork()) < 0)
        err_sys("fork error");
    else if (pid == 0)
        abort();

    if (waitid(P_PID, pid, &sif, WAIT_FLAG) < 0)
        err_sys("wait error");
    pr_siginfo(&sif);

    if ((pid = fork()) < 0)
        err_sys("fork error");
    else if (pid == 0)
        status /= 0;

    if (waitid(P_PID, pid, &sif, WAIT_FLAG) < 0)
        err_sys("wait error");
    pr_siginfo(&sif);

    exit(0);
}

void pr_siginfo(siginfo_t * siginfo)
{
    if (siginfo->si_signo == SIGCHLD && siginfo->si_code == CLD_EXITED)
        printf("normal termination, exit status = %d\n", siginfo->si_status);

    else if (siginfo->si_signo == SIGCHLD && siginfo->si_code == CLD_STOPPED)
        printf("child stopped, signal number = %d\n", siginfo->si_status);
    else
        printf("abnormal termination, signal number = %d%s\n", siginfo->si_status,
#ifdef WCOREDUMP
                (siginfo->si_code == CLD_DUMPED)? "core file generated": "");
#else
                "");
#endif
}

//void pr_exits(int status)
//{
//    if (WIFEXITED(status))
//        printf("normal termination, exit status = %d\n",
//                WEXITSTATUS(status));
//
//    else if (WIFSIGNALED(status))
//        printf("abnormal termination, signal number = %d%s\n",
//                WTERMSIG(status),
//#ifdef WCOREDUMP
//                WCOREDUMP(status) ? "(core file generated)": "");
//#else
//                "");
//#endif
//
//    else if (WIFSTOPPED(status))
//        printf("child stopped, signal number = %d\n",
//                WSTOPSIG(status));
//}
